package com.ken.common.web.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * Feign默认的拦截器
 * 拦截器作用：将当前服务的相关参数封装到当前请求的协议中，继续向下传递
 */
public class FeignDefaultRequestInterceptor implements RequestInterceptor {

    @Autowired
    private FeignProperties feignProperties;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获得需要传递的参数列表
        List<String> sendParamNames = feignProperties.getSendParamNames();
        System.out.println("参数：" + sendParamNames);
        //获得当前相关请求头
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获得所有请求头数据
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            //获得一个头数据名称
            String headerName = headerNames.nextElement();
            //获得对应的头数据value
            String headerValue = request.getHeader(headerName);
            //放入feign的请求中
            if (sendParamNames.contains(headerName)) {
                requestTemplate.header(headerName, headerValue);
            }
        }

        //获得所有请求参数数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //循环并设置参数
        for (Map.Entry<String, String[]> paramEntry : parameterMap.entrySet()) {
            if (sendParamNames.contains(paramEntry.getKey())) {
                requestTemplate.query(paramEntry.getKey(), paramEntry.getValue());
            }
        }
    }
}
